<template>
  <a-modal
    :title="title"
    :width="1200"
    :visible="visible"
    :maskClosable="false"
    :confirmLoading="confirmLoading"
    :okButtonProps="{ props: {disabled: disableSubmit} }"
    @ok="handleOk"
    @cancel="handleCancel">
    <a-spin :spinning="confirmLoading">
      <!-- 主表单区域 -->
      <a-form :form="form">
        <a-card type="inner" title="云服务清单">
          <a-row :gutter="24">
            <a-col :span="10">
              <a-form-item label="机构" :labelCol="labelCol" :wrapperCol="wrapperCol">
                <a-input v-decorator="['office',validatorRules.office]" :trigger-change="true" disabled="status" hidden="true" />
                <a-input v-decorator="['officeName',validatorRules.officeName]" :trigger-change="true" disabled="status" />
              </a-form-item>
            </a-col>
            <a-col :span="10">
              <a-form-item label="系统名称" :labelCol="labelCol" :wrapperCol="wrapperCol">
                <a-input v-decorator="[ 'systemName', validatorRules.systemName]" disabled="status" ></a-input>
              </a-form-item>
            </a-col>
          </a-row>
          <a-row :gutter="24">
            <a-col :md="10">
              <a-form-item
                :labelCol="labelCol"
                :wrapperCol="wrapperCol"
                label="开通时间">
                <a-input ref="openTime" v-decorator="[ 'openTime', validatorRules.openTime]"disabled="status" />
              </a-form-item>
            </a-col>
            <a-col :md="10">
              <a-form-item
                :labelCol="labelCol"
                :wrapperCol="wrapperCol"
                label="上次结算时间">
                <a-input  ref="lastPayTime" v-decorator="['lastPayTime', validatorRules.lastPayTime]" disabled="status"/>
              </a-form-item>
            </a-col>
          </a-row>
          <a-row :gutter="24">
            <a-col :md="10">
              <a-form-item
                :labelCol="labelCol"
                :wrapperCol="wrapperCol"
                label="未结算时长">
<!--                <a-input  v-decorator="[ 'noSetTime', validatorRules.noSetTime]" disabled="status" />-->
                <a-input  v-model="noSetTime"  ref="noSetTime" disabled="status" />
              </a-form-item>
            </a-col>
            <a-col :span="10">
              <a-form-item
                :labelCol="labelCol"
                :wrapperCol="wrapperCol"
                label="年云服务费">
                <a-input  v-decorator="[ 'yearMoney', validatorRules.yearMoney]"disabled="status" />
              </a-form-item>
            </a-col>
          </a-row>
          <a-row :gutter="24">
            <a-col :span="10">
              <a-form-item
                :labelCol="labelCol"
                :wrapperCol="wrapperCol"
                label="本期云服务费">
                <a-input ref="lastYearMoney" v-model="lastYearMoney" disabled="status" />
              </a-form-item>
            </a-col>
            <a-col :span="10">
<!--              <a-form-item-->
<!--                :labelCol="labelCol"-->
<!--                :wrapperCol="wrapperCol"-->
<!--                label="实际应付云服务费">-->
<!--                <a-input ref="payMoney" v-model="payMoney" disabled="status" />-->
<!--              </a-form-item>-->
                <a-form-item label="结算时间" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <j-date ref="payTime" v-decorator="[ 'thisPayTime']" @change="dateChange"></j-date>
                </a-form-item>
            </a-col>
          </a-row>
        </a-card>
      </a-form>

      <!-- 子表单区域 -->
      <a-tabs v-model="activeKey" @change="handleChangeTabs">
        <a-tab-pane tab="优惠项目" :key="refKeys[0]" :forceRender="true">
          <j-editable-table
            :ref="refKeys[0]"
            :loading="jinanGovernmentLedgerAttachedTable.loading"
            :columns="jinanGovernmentLedgerAttachedTable.columns"
            :dataSource="jinanGovernmentLedgerAttachedTable.dataSource"
            :maxHeight="300"
            :rowNumber="true"
            :rowSelection="true"
            :actionButton="true"/>
        </a-tab-pane>

      </a-tabs>

    </a-spin>
    <template slot="footer">
      <a-button key="back" @click="handleCancel">关闭</a-button>
      <a-button type="primary" :loading="confirmLoading" @click="handleOk">结算</a-button>
    </template>
  </a-modal>
</template>

<script>

  import pick from 'lodash.pick'
  import { FormTypes,getRefPromise } from '@/utils/JEditableTableUtil'
  // import JEditableTable  from './table/JEditableTable-cloud'
  // import JEditableTable  from '@/views/jinan/cloudApply/table/JEditableTable-cloud'
  // import { JEditableTableMixin } from '@/mixins/JEditableTableMixin-cloud'
  import { JEditableTableMixin } from '@/mixins/JEditableTableMixin'
  import JDate from '@/components/jeecg/JDate'
  import JSelectDepart from '@/components/jeecgbiz/JSelectDepart'
  import JMultiSelectTag from "@/components/dict/JMultiSelectTag"
  import JUpload from '@/components/jeecg/JUpload'
  import { getAction } from '@/api/manage'

  export default {
    name: 'cloudServiceMoneyModel2',
    mixins: [JEditableTableMixin],
    components: {
      JDate,
      // JEditableTable,
      JSelectDepart,
      JMultiSelectTag,
      JUpload
    },
    data() {
      return {
        payMoney:'',
        lastYearMoney:'',
        noSetTime:'',
        labelCol: {
          xs: { span: 22 },
          sm: { span: 6 }
        },
        wrapperCol: {
          xs: { span: 10 },
          sm: { span: 18}
        },
        disableSubmit:false,
        // 新增时子表默认添加几行空数据
        addDefaultRowNum: 1,
        validatorRules: {
          updateTime:{},
          office:{},
          principal:{},
          principalPhone:{rules: [{validator: this.validatePhone}]},
          principalMail:{rules: [{validator: this.validateEmail}]},
          linkman:{},
          linkmanPhone:{rules: [{validator: this.validatePhone}]},
          linkmanMail:{rules: [{validator: this.validateEmail}]},
          systemName:{},
          mainUses:{},
          tos:{},
        },
        refKeys: ['jinanGovernmentLedgerAttached', ],
        tableKeys:['jinanGovernmentLedgerAttached', ],
        activeKey: 'jinanGovernmentLedgerAttached',
        // 服务器申请附表
        jinanGovernmentLedgerAttachedTable: {
          loading: false,
          dataSource: [],
          columns: [
            {  //这一个隐藏字段不能去掉，解决360浏览器不兼容问题
              title: '优惠项目',
              key: '',
              type: FormTypes.hidden,
              defaultValue: '',
              placeholder: '请输入${title}',
              align:"center",
            },
            {
              title: '优惠项目',
              key: 'thisProject',
              type: FormTypes.input,
              defaultValue: '',
              placeholder: '请输入${title}',
              align:"center",
            },
            {
              title: '金额',
              key: 'thisProjectMoney',
              type: FormTypes.inputNumber,
              defaultValue: '',
              placeholder: '请输入${title}',
              align:"center",
            },
            {
              title: '说明',
              key: 'remaks',
              type: FormTypes.input,
              defaultValue: '',
              placeholder: '请输入${title}',
              align:"center",
            },

          ]
        },
        url: {
          add: "/jinanDredge/dredgeMain/pay",
          edit: "/jinanDredge/dredgeMain/pay",
          getMoney:"/jinanDredge/dredgeMain/getMoney"
          // jinanGovernmentLedgerAttached: {
          //   list: '/jinanServer/jinanGovernmentLedgerMain/queryJinanGovernmentLedgerAttachedByMainId'
          // },
        }
      }
    },
    methods: {
      dateChange(e){
        var table = this.$refs.jinanGovernmentLedgerAttached;
        // var ids = table.selectedRowIds;//选中的数据
        var values = table.getValuesSync().values;//获取所有数据
        const object={rowId:this.model.id,thisPayTime:e,date:this.$refs.lastPayTime.value,openTime:this.$refs.openTime.value}
        // const object = {rowId:obj.id,date:obj.lastPayTime,ip:obj.ipSite,thisPayTime:e,openTime:obj.openTime}
        // var  startDate =Date.parse(this.$refs.lastPayTime.value);
        // var  endDate = Date.parse(e);
        // var days=(endDate - startDate)/(24*60*60*1000);
        // if(days<0){
        //   days=0
        // }
          getAction(this.url.getMoney, object).then(res => {
            let money=res.data.auditMoney
            this.lastYearMoney=money;
            this.noSetTime=res.day.noSetTime;
            // table.setValues([{
            //   rowKey: obj.id,
            //   values: { thisPayTime:e,auditMoney: res.data.auditMoney, applyMoney: res.data.applyMoney,saveMoney:res.data.saveMoney }
            // }])
          }).finally(() => {
          })
      },
      /** 调用完edit()方法之后会自动调用此方法 */
      editAfter() {
        let rowNum = this.addDefaultRowNum;
        this.eachAllTable((item) => {
          item.add(rowNum)
        })

        let fieldval = pick(this.model,'office', 'officeName','systemName', 'serverName', 'noSetTime', 'openTime', 'lastPayTime', 'yearMoney', 'lastYearMoney')
        this.lastYearMoney=fieldval.lastYearMoney;
        this.noSetTime=fieldval.noSetTime;

      this.$nextTick(() => {
          this.form.setFieldsValue(fieldval)
        })
        // 加载子表数据
        // if (this.model.id) {
        //   let params = { id: this.model.id }
        //   this.requestSubTableData(this.url.jinanGovernmentLedgerAttached.list, params, this.jinanGovernmentLedgerAttachedTable)
        // }
      },
      /** 整理成formData */
      getAllTable() {
        let values = this.tableKeys.map(key => getRefPromise(this, key))
        return Promise.all(values)
      },
      classifyIntoFormData(allValues) {
        let lastYearMoney={lastYearMoney:this.$refs.lastYearMoney.value}

        let main = Object.assign(this.model, allValues.formValue)
        main.lastYearMoney=this.$refs.lastYearMoney.value;
        main.noSetTime=this.$refs.noSetTime.value;
        var table = this.$refs.jinanGovernmentLedgerAttached;
        var ids = table.selectedRowIds;//选中的数据
        var values = allValues.tablesValue[0].values;
        var arr = new Array();
        debugger;
        if(ids.length>0){//说明是自选
          values.forEach(value=>{
            ids.forEach(caseId=>{
              let id = caseId.split("-")[2];
              if(value.id==id){
                arr.push(value);
              }
            })
          })
        }else{//默认全部
          arr = values;
        }


        return {
          ...main, // 展开
          jinanGovernmentLedgerAttachedList: arr,
        }
      },
      validateError(msg){
        this.$message.error(msg)
      },
      validateEmail(rule, value, callback){
        if(!value){
          callback()
        }else{
          if(new RegExp(/^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.[a-zA-Z0-9]{2,6}$/).test(value)){
            callback()
          }else{
            callback("请输入正确格式的邮箱!")
          }
        }
      },
      validatePhone(rule, value, callback){
        if(!value){
          callback()
        }else{
          if(new RegExp(/(\(\d{3,4}\)|\d{3,4}-|\s)?\d{7,14}/).test(value)){
            callback()
          }else{
            callback("请输入正确格式的电话号码!");
          }
        }
      },
      /** 删除被选中的行 */
      removeSelectedRows() {
        debugger
        this.removeRows(this.selectedRowIds)
        this.selectedRowIds = []
      },
      /** 删除
       *
一行或多行 */
      handleConfirmDelete() {
        this.removeSelectedRows()
      },
      removeRows(id) {
        debugger
        let ids = id
        if (!(id instanceof Array)) {
          if (typeof id === 'string') {
            ids = [id]
          } else {
            throw  `JEditableTable.removeRows() 函数需要的参数可以是string或Array类型，但提供的却是${typeof id}`
          }
        }

        let rows = cloneObject(this.rows)
        ids.forEach(removeId => {
          // 找到每个id对应的真实index并删除
          const findAndDelete = (arr) => {
            for (let i = 0; i < arr.length; i++) {
              if (arr[i].id === removeId || arr[i].id === this.caseId + removeId) {
                arr.splice(i, 1)
                return true
              }
            }
          }
          // 找到rows对应的index，并删除
          if (findAndDelete(rows)) {
            // 找到values对应的index，并删除
            findAndDelete(this.inputValues)
            // 将caseId去除
            let id = this.removeCaseId(removeId)
            this.deleteIds.push(id)
          }
        })
        this.rows = rows
        this.$emit('deleted', this.getDeleteIds())
        this.$nextTick(() => {
          // 更新formValues
          this.updateFormValues()
        })
        return true
      },
      handleDelete(props) {
        debugger
        // 参数解释
        // props.index ：当前行的下标
        // props.text ：当前值，可能是defaultValue定义的值，也可能是从dataSource中取出的值
        // props.rowId ：当前选中行的id，如果是新增行则是临时id
        // props.column ：当前操作的列
        // props.getValue ：这是一个function，执行后可以获取当前行的所有值（禁止在template中使用）
        //                  例：const value = props.getValue()
        // props.target ：触发当前事件的实例，可直接调用该实例内的方法（禁止在template中使用）
        //                  例：target.add()

        // 使用实例：删除当前操作的行
        let { rowId, target } = props
        target.removeRows(rowId)
      },

      // handleOk() {
      //   debugger
      //   /** 触发表单验证 */
      //   this.getAllTable().then(tables => {
      //     /** 一次性验证主表和所有的次表 */
      //     return validateFormAndTables(this.form, tables)
      //   }).then(allValues => {
      //     if (typeof this.classifyIntoFormData !== 'function') {
      //       throw this.throwNotFunction('classifyIntoFormData')
      //     }
      //     let formData = this.classifyIntoFormData(allValues)
      //
      //     return this.request(formData)
      //   }).catch(e => {
      //     // if (e.error === VALIDATE_NO_PASSED) {
      //     //   // 如果有未通过表单验证的子表，就自动跳转到它所在的tab
      //     //   this.activeKey = e.index == null ? this.activeKey : this.refKeys[e.index]
      //     // } else {
      //     //   console.error(e)
      //     // }
      //   })
      // },
    }
  }
</script>

<style scoped>
</style>